const { PrismaClient } = require('@prisma/client');

const prisma = new PrismaClient();

async function testAdminPermissions() {
  try {
    console.log('检查超级管理员权限...');
    
    // 查找超级管理员用户
    const adminUser = await prisma.user.findUnique({
      where: { username: 'admin' },
      include: {
        userRoles: {
          include: {
            role: {
              include: {
                rolePermissions: {
                  include: {
                    permission: true
                  }
                }
              }
            }
          }
        }
      }
    });

    if (!adminUser) {
      console.log('❌ 超级管理员用户不存在');
      return;
    }

    console.log(`✅ 找到超级管理员用户: ${adminUser.username}`);
    console.log(`用户状态: ${adminUser.status}`);

    // 检查角色
    const roles = adminUser.userRoles.map(ur => ur.role.name);
    console.log(`用户角色: ${roles.join(', ')}`);

    // 检查权限
    const permissions = adminUser.userRoles.flatMap(ur => 
      ur.role.rolePermissions.map(rp => rp.permission.code)
    );

    console.log(`用户权限数量: ${permissions.length}`);
    console.log('用户权限列表:');
    permissions.forEach(permission => {
      console.log(`  - ${permission}`);
    });

    // 检查是否有 role:read 权限
    const hasRoleReadPermission = permissions.includes('role:read');
    console.log(`\n是否有 role:read 权限: ${hasRoleReadPermission ? '✅ 是' : '❌ 否'}`);

    // 检查所有角色相关权限
    const rolePermissions = permissions.filter(p => p.startsWith('role:'));
    console.log(`\n角色相关权限:`);
    rolePermissions.forEach(permission => {
      console.log(`  - ${permission}`);
    });

    // 检查数据库中所有权限
    console.log('\n=== 检查数据库中的所有权限 ===');
    const allDbPermissions = await prisma.permission.findMany({
      orderBy: { code: 'asc' }
    });
    
    console.log(`数据库中的权限总数: ${allDbPermissions.length}`);
    console.log('数据库中的权限列表:');
    allDbPermissions.forEach(permission => {
      console.log(`  - ${permission.code} (${permission.name})`);
    });

    // 检查角色相关权限是否在数据库中
    const rolePermissionsInDb = allDbPermissions.filter(p => p.code.startsWith('role:'));
    console.log(`\n数据库中的角色相关权限:`);
    rolePermissionsInDb.forEach(permission => {
      console.log(`  - ${permission.code} (${permission.name})`);
    });

  } catch (error) {
    console.error('测试失败:', error);
  } finally {
    await prisma.$disconnect();
  }
}

testAdminPermissions(); 